# ui/dialogs.py - 完整修复版本
import tkinter as tk
from tkinter import ttk, messagebox, filedialog, simpledialog, Menu
import os
from pathlib import Path

from models.package_info import PackageInfo
from utils.validation_utils import validate_package_name

def show_file_operations_menu(root, file_listbox, file_list_map, delete_callback, rename_callback):
    """显示文件操作菜单"""
    selection = file_listbox.curselection()
    if not selection:
        return
    
    index = selection[0]
    if index >= len(file_list_map):
        return
    
    # 创建文件操作菜单
    file_ops_menu = Menu(root, tearoff=0)
    file_ops_menu.add_command(label="删除", command=delete_callback)
    file_ops_menu.add_command(label="重命名", command=rename_callback)
    
    # 在文件列表附近显示菜单
    file_list_frame = file_listbox.master
    x = file_list_frame.winfo_rootx() + file_list_frame.winfo_width() // 2
    y = file_list_frame.winfo_rooty() + file_list_frame.winfo_height() // 2
    
    file_ops_menu.post(x, y)

def show_create_package_dialog(root, config, download_manager, auth_manager, callback=None):
    """显示创建包对话框"""
    dialog = tk.Toplevel(root)
    dialog.title("新建文件包")
    dialog.geometry("500x400")
    dialog.transient(root)
    dialog.grab_set()
    
    # 名称
    ttk.Label(dialog, text="名称:").pack(anchor=tk.W, pady=(10, 5), padx=10)
    name_var = tk.StringVar()
    name_entry = ttk.Entry(dialog, textvariable=name_var, width=50)
    name_entry.pack(fill=tk.X, padx=10, pady=(0, 10))
    
    # 简述
    ttk.Label(dialog, text="简述:").pack(anchor=tk.W, pady=(0, 5), padx=10)
    brief_var = tk.StringVar()
    brief_entry = ttk.Entry(dialog, textvariable=brief_var, width=50)
    brief_entry.pack(fill=tk.X, padx=10, pady=(0, 10))
    
    # 简介
    ttk.Label(dialog, text="简介:").pack(anchor=tk.W, pady=(0, 5), padx=10)
    description_text = tk.Text(dialog, height=6, width=50)
    description_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
    
    # 图像选择
    image_frame = ttk.Frame(dialog)
    image_frame.pack(fill=tk.X, padx=10, pady=(0, 10))
    
    image_var = tk.StringVar(value="未选择图像（可选）")
    ttk.Label(image_frame, textvariable=image_var).pack(side=tk.LEFT, fill=tk.X, expand=True)
    
    image_path = None
    
    def select_image():
        nonlocal image_path
        filename = filedialog.askopenfilename(
            title="选择预览图像",
            filetypes=[("PNG图像", "*.png")]
        )
        if filename:
            # 验证图像格式
            if not filename.lower().endswith('.png'):
                messagebox.showwarning("警告", "只支持PNG格式图像")
                return
            
            image_path = filename
            image_var.set(Path(filename).name)
    
    ttk.Button(image_frame, text="选择图像", command=select_image).pack(side=tk.RIGHT)
    
    # 协议确认
    agreement_var = tk.BooleanVar()
    agreement_check = ttk.Checkbutton(
        dialog, 
        text="我同意遵守相关协议（必须遵守法律法规，不得上传违法内容）",
        variable=agreement_var
    )
    agreement_check.pack(anchor=tk.W, padx=10, pady=(0, 10))
    
    # 按钮框架
    button_frame = ttk.Frame(dialog)
    button_frame.pack(fill=tk.X, padx=10, pady=10)
    
    def create_package():
        """创建包"""
        # 验证输入
        name = name_var.get().strip()
        brief = brief_var.get().strip()
        description = description_text.get("1.0", tk.END).strip()
        
        if not name:
            messagebox.showwarning("警告", "请输入名称")
            return
        
        if not validate_package_name(name):
            messagebox.showwarning("警告", "名称只能包含字母、数字、下划线和连字符")
            return
        
        if not brief:
            messagebox.showwarning("警告", "请输入简述")
            return
        
        if not description:
            messagebox.showwarning("警告", "请输入简介")
            return
        
        if not agreement_var.get():
            messagebox.showwarning("警告", "请同意相关协议")
            return
        
        # 验证权限
        if not auth_manager.has_upload_permission():
            password = ask_for_password(root)
            if not password:
                return
            if not auth_manager.check_upload_permission(password):
                messagebox.showerror("错误", "权限验证失败")
                return
        
        # 创建包信息
        package_info = PackageInfo(
            name=name,
            brief=brief,
            description=description
        )
        
        # 创建包
        success = download_manager.create_new_package(package_info, image_path)
        
        if success:
            messagebox.showinfo("成功", "文件包创建成功")
            dialog.destroy()
            if callback:
                callback(True)
        else:
            messagebox.showerror("错误", "文件包创建失败")
    
    def cancel():
        dialog.destroy()
        if callback:
            callback(False)
    
    ttk.Button(button_frame, text="创建", command=create_package).pack(side=tk.LEFT, padx=(0, 10))
    ttk.Button(button_frame, text="取消", command=cancel).pack(side=tk.LEFT)
    
    # 绑定回车键
    dialog.bind('<Return>', lambda e: create_package())
    name_entry.focus()

def show_edit_package_dialog(root, config, download_manager, auth_manager, 
                           package_name, package_info, callback=None):
    """显示编辑包对话框"""
    dialog = tk.Toplevel(root)
    dialog.title(f"编辑文件包 - {package_name}")
    dialog.geometry("500x350")
    dialog.transient(root)
    dialog.grab_set()
    
    # 简述
    ttk.Label(dialog, text="简述:").pack(anchor=tk.W, pady=(10, 5), padx=10)
    brief_var = tk.StringVar(value=package_info.brief)
    brief_entry = ttk.Entry(dialog, textvariable=brief_var, width=50)
    brief_entry.pack(fill=tk.X, padx=10, pady=(0, 10))
    
    # 简介
    ttk.Label(dialog, text="简介:").pack(anchor=tk.W, pady=(0, 5), padx=10)
    description_text = tk.Text(dialog, height=6, width=50)
    description_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
    description_text.insert("1.0", package_info.description)
    
    # 图像选择
    image_frame = ttk.Frame(dialog)
    image_frame.pack(fill=tk.X, padx=10, pady=(0, 10))
    
    image_var = tk.StringVar(value="未选择新图像（可选）")
    ttk.Label(image_frame, textvariable=image_var).pack(side=tk.LEFT, fill=tk.X, expand=True)
    
    image_path = None
    
    def select_image():
        nonlocal image_path
        filename = filedialog.askopenfilename(
            title="选择预览图像",
            filetypes=[("PNG图像", "*.png")]
        )
        if filename:
            # 验证图像格式
            if not filename.lower().endswith('.png'):
                messagebox.showwarning("警告", "只支持PNG格式图像")
                return
            
            image_path = filename
            image_var.set(Path(filename).name)
    
    ttk.Button(image_frame, text="选择图像", command=select_image).pack(side=tk.RIGHT)
    
    # 协议确认
    agreement_var = tk.BooleanVar()
    agreement_check = ttk.Checkbutton(
        dialog, 
        text="我同意遵守相关协议（必须遵守法律法规，不得上传违法内容）",
        variable=agreement_var
    )
    agreement_check.pack(anchor=tk.W, padx=10, pady=(0, 10))
    
    # 按钮框架
    button_frame = ttk.Frame(dialog)
    button_frame.pack(fill=tk.X, padx=10, pady=10)
    
    def update_package():
        """更新包"""
        # 验证输入
        brief = brief_var.get().strip()
        description = description_text.get("1.0", tk.END).strip()
        
        if not brief:
            messagebox.showwarning("警告", "请输入简述")
            return
        
        if not description:
            messagebox.showwarning("警告", "请输入简介")
            return
        
        if not agreement_var.get():
            messagebox.showwarning("警告", "请同意相关协议")
            return
        
        # 验证权限
        if not auth_manager.has_upload_permission():
            password = ask_for_password(root)
            if not password:
                return
            if not auth_manager.check_upload_permission(password):
                messagebox.showerror("错误", "权限验证失败")
                return
        
        # 更新包信息
        success = download_manager.update_package_info(
            package_name, brief, description, image_path
        )
        
        if success:
            messagebox.showinfo("成功", "文件包信息更新成功")
            dialog.destroy()
            if callback:
                callback(True)
        else:
            messagebox.showerror("错误", "文件包信息更新失败")
    
    def cancel():
        dialog.destroy()
        if callback:
            callback(False)
    
    ttk.Button(button_frame, text="更新", command=update_package).pack(side=tk.LEFT, padx=(0, 10))
    ttk.Button(button_frame, text="取消", command=cancel).pack(side=tk.LEFT)
    
    # 绑定回车键
    dialog.bind('<Return>', lambda e: update_package())
    brief_entry.focus()

def ask_for_password(parent):
    """请求输入密码"""
    password = simpledialog.askstring(
        "权限验证",
        "请输入管理员密码:",
        show='*',
        parent=parent
    )
    return password